import { DictionaryItem, DictType, DicTypeRq } from "./models";
import req from "/@/api/req";

export enum Api {
  addDictionary = "api/system/dictionary/addDictionary",
  deleteDictionaryByIds = "api/system/dictionary/deleteDictionaryByIds",
  getDictionary = "api/system/dictionary/getDictionary",
  getDictionaryByType = "api/system/dictionary/getDictionaryByType",
  updateDictionary = "api/system/dictionary/updateDictionary",

  deleteDictionaryTypeByIds = "api/system/dictionary/deleteDictionaryTypeByIds",
  updateDictionaryType = "api/system/dictionary/updateDictionaryType",
  addDictionaryType = "api/system/dictionary/addDictionaryType",
  getDictionaryType = "api/system/dictionary/getDictionaryType",
}

export function getDictionaryByType(params: DicTypeRq) {
  return req.get<Array<DictionaryItem>>(
    {
      url: Api.getDictionaryByType,
      params,
    },
    {
      useGlobalLoading: false,
    }
  );
}

const dictCache: Record<DictType, DictionaryItem[]> | {} = {};
export async function getDictWithCache(
  dictType: DictType,
  { noCache, loading }: { noCache: boolean; loading: boolean }
): Promise<DictionaryItem[]> {
  let target = dictCache[dictType];
  if (!target || noCache) {
    if (loading === undefined) loading = true;
    target = await req.commonGet(Api.getDictionaryByType, { dictionaryType: dictType }, { useGlobalLoading: loading });
    if (!target) return [];
    dictCache[dictType] = target;
    return target;
  }
  return target;
}
